const { Controller } = require("egg");

class TopicLessonExamController extends Controller {
  async createExamRecord() {
    const { lessonId, userId, exams } = this.ctx.request.body;
    if (!lessonId || !userId || !exams) {
      return this.ctx.helper.error("参数异常：缺少lessonId、userId或exams");
    }
    try {
      const createdRecord = await this.service.topicLessonExam.create({
        lessonId: this.ctx.helper.toInt(lessonId),
        userId,
        exams,
        answers: '', // 初始化答题结果为空
      });
      if (!createdRecord) {
        return this.ctx.helper.error("创建考试记录失败");
      }
      this.ctx.helper.success(createdRecord, "考试记录创建成功");
    } catch (error) {
      this.ctx.helper.error("创建考试记录失败：" + error.message);
    }
  }

  async getExamRecord() {
    const { id } = this.ctx.query;
    if (!id) {
      return this.ctx.helper.error("参数异常：缺少考试记录id");
    }
    try {
      const record = await this.service.topicLessonExam.id(this.ctx.helper.toInt(id));
      if (!record) {
        return this.ctx.helper.error("未找到考试记录");
      }
      this.ctx.helper.success(record, "考试记录查询成功");
    } catch (error) {
      this.ctx.helper.error("查询考试记录失败：" + error.message);
    }
  }

  async updateAnswers() {
    const { lessonId, userId, answers } = this.ctx.request.body;
    if (!lessonId || !userId || !answers) {
      return this.ctx.helper.error("参数异常：缺少lessonId、userId或answers");
    }
    try {
      const updatedRecord = await this.service.topicLessonExam.updateAnswers({
        lessonId: this.ctc.helper.toInt(lessonId),
        userId,
        answers,
      });
      if (!updatedRecord) {
        return this.ctx.helper.error("更新答题结果失败");
      }
      this.ctx.helper.success(updatedRecord, "答题结果更新成功");
    } catch (error) {
      this.ctx.helper.error("更新答题结果失败：" + error.message);
    }
  }
}

module.exports = TopicLessonExamController;